<template>
  <div style="max-height: 50vh;overflow: auto">
    <el-form label-width="80px" :model="sendForm" :rules="sendRules" ref="sendRef">
      <div style="display: flex;">
        <el-form-item label="发货仓库" prop="shopId">
          <el-select v-model="shopName" value-key="id"  :filter-method="remoteMethodshop"  filterable placeholder="请选择" @change="selectShop">
            <el-option
              style="width:600px"
              v-for="item in shopList"
              :key="item.id"
              :label="item.name"
              :value="item"
            >
              <div style="display: flex">
                <span style="float: left;width: 150px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                <span style="width: 100px;">{{item.distance?item.distance:'无'}}</span>
                <div style="width: 200px;">
                  <span style="color: #8492a6; font-size: 8px;">{{item.address}}</span>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="送货员" style="margin-left: 10px;" v-if="sendForm.order.shippingMethod==2 && unionType!=4">
          <el-select style="width: 100%" v-model="operatorName" value-key="id" filterable placeholder="请选择"
                     @change="selectSysEmployee">
            <el-option
              v-for="item in sysEmployeeList"
              :key="item.id"
              :label="item.name"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货日期" style="margin-left: 10px;" prop="orderDate">
          <el-date-picker
            style="width: 140px"
            value-format="yyyy-MM-dd"
            v-model="sendForm.orderDate"
            align="right"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>

      </div>
      <el-form-item label="收货地址" prop="address" style="width: 575px">
        <span>{{sendData.address}}</span>
        <!-- <el-select style="width: 100%" v-model="sendData.address" value-key="id" filterable placeholder="请选择"
                   @change="changeAddress">
          <el-option
            v-for="item in receiverForm"
            :key="item.id"
            :label="item.address"
            :value="item">
          </el-option>
          <el-option style="background-color: #f9f9f9;text-align: center;" key="*" label="底部隐藏块"
                     value="*"></el-option>
          <el-option style="background-color: #f9f9f9;text-align: center;position: absolute;bottom:0;width: 100%" key="#" label="--- 新增收货地址 ---"
                     value="#"></el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="收货人" >
        <div style="display: flex;align-items: flex-end">
          <div style="display: flex; flex-direction: column;">
            <span>{{ sendForm.order.consignee }} {{ sendForm.order.phone }}</span>
          </div>
        </div>
      </el-form-item>
      <div style="display: flex;">
        <el-form-item label="配送时间" v-show="bomType==1">
          <div style="display: flex; flex-direction: column;">
            <el-select v-model="weekDate" multiple placeholder="请选择" @change="weekClick">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <span>预计送达时间：{{date | dateFormatter}}</span>
          </div>
        </el-form-item>
        <el-form-item label="送货备注">
          <div style="display: flex; flex-direction: row">
            <el-input style="width:210px;" v-model="memo" placeholder="请输入内容" ></el-input>
          </div>
        </el-form-item>
      </div>
      <div class="product_header_name">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">商品明细</span>
      </div>
      <el-table
        :data="sendData.itemList"
        border
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="50"
          align="center"
          fixed
        />
        <el-table-column
          prop="name"
          label="姓名"
          width="180"
        />
        <el-table-column
          prop="spec"
          label="规格"
        />
        <el-table-column
          prop="quantity"
          label="订单数量"
        />
        <el-table-column
          prop="availableShippedQuantity"
          label="待发数量"
        />
        <el-table-column
          fixed="right"
          prop="shippedQuantity"
          label="发货数量"
        >
          <template slot-scope="scope">
            <el-input type="number" @input="numberInput($event,scope.$index)" v-model="scope.row.shippedQuantity" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <office-dialog ref="officeDialog" @confirm="dialogConfirm" />
    <el-dialog
      title="新增地址"
      :visible.sync="receiverVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="receiverClose">
      <div style="position: relative;height: 60vh;overflow: auto">
        <!--          <memberAdd :memberType="memberType" @memberClick="memberClick"></memberAdd>-->
        <receiverAdd  @orderReceiver="orderReceiver" pathType="0" :memberId="sendData.memberId"></receiverAdd>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {receiverLocation} from '@/api/mapLine'
  import {list as addressList} from '@/api/receiver'
  import {EventBus} from '@/api/eventBus'
  import receiverAdd from '@/views/receiver/add'
  import utils from '../../../utils/utils'
  import OfficeDialog from '@/components/OfficeDialog'
  import { list as sysEmployeeList } from '@/api/sysEmployee'
  import {lbsList ,find as shopFind} from '@/api/shop'
  import {update as memberupdate} from '@/api/member'
  import { shipping, shippingAndAudit ,calculateEstimateDate,updateWeekAndReceiver} from '@/api/order'
  import { audit } from '@/api/warehouse'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  export default {
    directives: {elDragDialog},
    components: {
      OfficeDialog,receiverAdd
    },
    props: ['sendForm','weekType','memberMemo','bomType'],
    data() {
      return {
        shoplat:0,
        shoplng:0,
        memo:null,
        address:{},
        sendData: {
          memberId: '',
          address: '',
          itemList: [],
          officeId: '',
          operatorId: ''
        },
        options: [{
          value: '1',
          label: '周一'
        }, {
          value: '2',
          label: '周二'
        }, {
          value: '3',
          label: '周三'
        }, {
          value: '4',
          label: '周四'
        }, {
          value: '5',
          label: '周五'
        },{
          value: '6',
          label: '周六'
        },{
          value: '7',
          label: '周七'
        }],
        date:'',
        receiverId:'',
        weekDate:[],
        receiverForm:[],
        receiverVisible:false,
        weekTime: '',
        currentRow:null,
        addressType:false,
        orderDate: '',
        shopId: '',
        shopName: '',
        officeName: '',
        operatorName: '',
        memberName: '',
        sysEmployeeList: [],
        shopList: [],
        unionType:0,
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now()
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }]
        },
        sendRules: {
//        orderDate: [
//          { required: true, message: '请选择日期', trigger: 'blur' },
//        ],
//        shopId: [
//          { required: true, message: '请选择仓库', trigger: 'blur' },
//        ],

        }
      }
    },
    created() {
      if (!utils.isNull(this.sendForm)) {
        console.log(this.sendForm)
        this.memberName = this.sendForm.memberName
        this.sendData.address = this.sendForm.order.address
        this.sendData.itemList = this.sendForm.order.itemList
        this.sendData.memberId = this.sendForm.order.memberId
        this.sendData.officeId = this.sendForm.order.officeId
        this.receiverId=this.sendForm.order.receiverId
        this.sendData.operatorId = this.sendForm.order.operatorId
        this.officeName = this.sendForm.officeName
        // this.operatorName = this.sendForm.operatorName
        this.sendData.itemList.forEach(item => { // 初始化发货数量
          item.shippedQuantity = item.availableShippedQuantity
        })

        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth() + 1 + ''
        let day = date.getDate() + ''
        this.$set(this.sendForm, 'orderDate', `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`)
        if (!utils.isNull(this.sendForm.order.weekTime) && this.weekType == true) {
          this.weekTime = this.sendForm.order.weekTime
          this.weekDate = this.sendForm.order.weekTime.split("")
          this.calculateEstimateDateClick()
        }
        // this.sendForm.orderDate = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
      }
      this.loadShop("")
      this.loadReceiver()
      this.loadSysEmployee('')
      if (this.sendForm.order.shippingMethod==2){
        this.loadMapLine(this.receiverId)
      }
      console.log(this.sendData)
    },
    watch:{
      shopName(newName,oldName){
        this.unionClick()
        console.log(newName)
        console.log('我监听到啦仓库')
      }
    },
    mounted(){
      this.memo=this.memberMemo
      if(!utils.isNull(this.sendForm.order.lat)){
        this.shoplat=this.sendForm.order.lat
        this.shoplng=this.sendForm.order.lng
      }
    },
    methods: {
      receiverClose() {
        this.receiverVisible = false;
      },
      loadMapLine(query){
        let params=new URLSearchParams()
        params.append('receiverId',query)
        receiverLocation(params).then(res=>{
          this.sendForm.shopName=res.data.mapLine.shopName
          this.sendForm.shopId=res.data.mapLine.shopId
          this.shopId=res.data.mapLine.shopId
          this.shopName=res.data.mapLine.shopName
          this.operatorName=res.data.shippingEmployeeName
          this.shippingEmployeeId=res.data.mapLine.shippingEmployeeId
        })
      },
      changeAddress(data){
        var _this=this
        if (data == '#') {
          _this.receiverVisible = true;
          this.sendForm.order.address = ''
        } else {

          _this.receiverId=data.id
          _this.loadMapLine(_this.receiverId)
          _this.sendForm.address = data.address
          _this.sendForm.order.areaName = data.areaName
          _this.sendForm.order.areaId = data.areaId;
          _this.sendForm.order.consignee = data.consignee;
          _this.sendForm.order.phone = data.phone
        }
        console.log(data)
      },
      numberInput (value, index) { // 限制最大发货数量跟最小发货数量
        console.info("value" + value)
        console.info("this.sendData.itemList[index].availableShippedQuantity" + this.sendData.itemList[index].availableShippedQuantity)
        if (value > this.sendData.itemList[index].availableShippedQuantity) {
          console.info("我进判断了")
          this.sendData.itemList[index].shippedQuantity = this.sendData.itemList[index].availableShippedQuantity
          console.info("this.sendData.itemList[index].shippedQuantity" + this.sendData.itemList[index].shippedQuantity)
        }
      },
      orderReceiver(data) {
        var _this = this;
        console.log(data)
        _this.receiverForm.push(data.data)
        _this.receiverId=data.data.id
        _this.sendForm.order.address = data.data.address
        _this.sendForm.address=data.data.address
        _this.sendForm.order.areaName = data.data.areaName
        _this.sendForm.order.areaId = data.data.areaId;
        _this.sendForm.order.consignee = data.data.consignee;
        _this.sendForm.order.phone = data.data.phone;
        _this.receiverClose()
      },
      chooseClick() {
        var _this = this
        if (_this.receiverId == '') {
          _this.$message({
            message: '请选择地址',
            offset: 120,
            center: true
          })
          return
        }
        const params = new URLSearchParams()
        params.append('orderId', _this.form.id)
        params.append('receiverId', _this.receiverId)
        updateWeekAndReceiver(params).then(res => {
          console.log(res)
          _this.$message({
            message: '修改成功',
            offset: 120,
            center: true
          })
          _this.addressType = false
          _this.receiverId = ''
          _this.$emit('findClick')
        }).catch(err => {
          console.log(err)
        })
      },
      //  销售公司
      dialogShow() {
        console.log('点击了')
        this.$refs.officeDialog.show()
      },
      handleCurrentChange(val) {
        console.log(val)
        this.currentRow = val;
        this.receiverId = val.id
      },
      //  修改地址
      addressClose() {
        var _this = this
        _this.addressType = false
        this.receiverId = ''
      },
      dialogConfirm(val) {
        this.sendData.officeId = val.id
        this.officeName = val.name
      },
      selectShop(data) {
        console.log("2222222")
        console.log(data)
        this.shopId = data.id
        this.sendForm.shopId=data.id
        this.sendForm.shopName=data.name
        this.shopName=data.name
      },
      addressClick() {
        var _this = this
        _this.loadReceiver()
        _this.addressType = true
      },
      loadReceiver() {
        var _this = this
        const params = new URLSearchParams()
        params.append('memberId',  this.sendData.memberId)
        addressList(params).then(res => {

          _this.receiverForm = res.data.data
          console.log(  _this.receiverForm )
        }).catch(err => {
          console.log(err)
        })
      },
      selectSysEmployee(data) {
        this.shippingEmployeeId = data.id
        this.operatorName=data.name
      },
      //  业务员
      loadSysEmployee(query) {
        var _this = this
        const params = new URLSearchParams()
        params.append('name',query)
        params.append('pageSize',1000)
        sysEmployeeList(params).then(response => {

          _this.sysEmployeeList = response.data.data
        }).catch(error => {
          console.log('error!!')
        })
      },
      remoteMethodshop(data){
        this.loadShop(data)
      },
      //  仓库
      loadShop(query) {
        var _this = this
        const params = new URLSearchParams()
        params.append('keyword', query)
        params.append('lat', this.shoplat)
        params.append('lng', this.shoplng)
        lbsList(params).then(response => {
          console.log(response)
          _this.shopList = response.data
          this.shopList.forEach(item=>{
            item.distance=item.distance.toFixed(2)
          })
          if (_this.shopList.length>0) {
            this.shopId = _this.shopList[0].id
            this.sendForm.shopId=_this.shopList[0].id
            this.sendForm.shopName=_this.shopList[0].name
            this.shopName=_this.shopList[0].name

          }


        }).catch(error => {
          console.log('error!!')
        })
      },
      delivery() {
        var adopt = 0 // 用于判断发货量是否小于0
        this.sendData.itemList.forEach(item => {
          console.info("item"+JSON.stringify(item))
          if (item.shippedQuantity > 0) {
            adopt = adopt + item.shippedQuantity
          }
        })
        this.$refs.sendRef.validate((valid) => {
          if (adopt==0) {
            _this.$emit('deliveryClone')
            return this.$message({message: '请输入发货数量',type: 'warning'})
          }
          if (valid) {
            var _this = this
            const params = new URLSearchParams()
            params.append('shopId', _this.shopId)

            if (_this.shippingEmployeeId!=undefined){

              params.append('shippingEmployeeId',_this.shippingEmployeeId)
            }
            if (_this.receiverId!=undefined){
              params.append('receiverId',_this.receiverId)
            }
            params.append('orderDate', _this.sendForm.orderDate)
            params.append('weekTime',_this.weekTime)
            params.append('memo',_this.memo)

            shipping(_this.sendForm.order.id, params, _this.sendData.itemList).then(response => {
              console.log(response)
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              })
              _this.$emit('findClick')
              _this.$emit('sendClose')
              EventBus.$emit('order-view', response.data)
              if (this.weekType==true){
                _this.memberClick()
              }

            }).catch(error => {
              _this.$emit('deliveryClone')
              console.log('error!!')
            })
          }else{
            _this.$emit('deliveryClone')
          }
        })
      },
      aDeliveryClick() {
        var adopt = 0 // 用于判断发货量是否小于0
        this.sendData.itemList.forEach(item => {
          if (item.shippedQuantity > 0) {
            adopt = adopt + item.shippedQuantity
          }
        })
        this.$refs.sendRef.validate((valid) => {
          if (adopt==0) {
            return this.$message({message: '请输入发货数量',type: 'warning'})
          }
          if (valid) {
            var _this = this
            const params = new URLSearchParams()
            params.append('shopId', _this.shopId)
            if (_this.shippingEmployeeId!=undefined){

              params.append('shippingEmployeeId',_this.shippingEmployeeId)
            }
            if (_this.receiverId!=undefined){
              params.append('receiverId',_this.receiverId)
            }
            params.append('orderDate', _this.sendForm.orderDate)
            params.append('weekTime',this.weekTime)
            params.append('memo',this.memo)

            shippingAndAudit(_this.sendForm.order.id, _this.sendData.itemList, params).then(response => {
              console.log(response)
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              })
              _this.$emit('findClick')
              _this.$emit('sendClose')
              EventBus.$emit('order-view', response.data)
              if (this.weekType==true){
                _this.memberClick()
              }
            }).catch(error => {
              console.log('error!!')
            })
          }
        })
      },
      weekClick(data){

        this.weekTime = data.join('')
        this.calculateEstimateDateClick()
      },
      calculateEstimateDateClick(){
        var _this = this
        console.log(_this.weekTime)
        const params = new URLSearchParams()
        params.append('week', _this.weekTime)
        calculateEstimateDate(params).then(response => {
          console.log(response)
          _this.date = response.data.estimateDate
        }).catch(error => {
          console.log('error!!')
        })
      },
      memberClick() {
        var _this = this

        if (_this.memberMemo!=null){
          var form = {
            id:this.sendForm.order.memberId,
            memo: _this.memberMemo
          }
          memberupdate(form).then(response => {
            this.$message({
              message: 修改成功,
              offset: 120,
              center: true
            })
          }).catch(error => {

          })
        }

      },
      unionClick(){
        var _this = this
        shopFind(this.shopId).then(res=>{
          _this.unionType = res.data.shop.type
          console.log(res)
          console.log('我这店铺')
        })
      }
    }
  }
</script>

<style scoped>
  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
</style>
